<template>
    <div class="payment">
        <van-nav-bar title="支付管理" left-text="返回" left-arrow @click-left="onClickLeft" />

        <div class="payment-content">
            <!-- 支付方式列表 -->
            <div class="payment-list" v-if="payments.length">
                <van-cell-group inset title="已添加的支付方式">
                    <van-cell v-for="item in payments" :key="item.id" :class="{ 'default-payment': item.isDefault }">
                        <template #title>
                            <div class="payment-item">
                                <div class="payment-icon">
                                    <van-icon :name="getPaymentIcon(item.type)" size="24"
                                        :color="getPaymentColor(item.type)" />
                                </div>
                                <div class="payment-info">
                                    <div class="payment-name">
                                        {{ item.name }}
                                        <van-tag v-if="item.isDefault" type="primary" size="small"
                                            color="#ff9854">默认</van-tag>
                                    </div>
                                    <div class="payment-account">{{ hideAccount(item.account) }}</div>
                                    <div class="payment-expiry" v-if="item.expiry">有效期至: {{ item.expiry }}</div>
                                </div>
                            </div>
                        </template>
                        <template #right-icon>
                            <div class="payment-actions">
                                <van-button size="small" type="primary" color="#ff9854" plain
                                    @click="setDefault(item.id)" :disabled="item.isDefault">
                                    设为默认
                                </van-button>
                                <van-button size="small" type="danger" @click="deletePayment(item.id)"
                                    :disabled="item.isDefault">
                                    删除
                                </van-button>
                            </div>
                        </template>
                    </van-cell>
                </van-cell-group>
            </div>

            <div class="empty-state" v-else>
                <van-empty image="search" description="您还未添加支付方式" />
            </div>

            <div class="add-payment-btn">
                <van-button block round icon="plus" type="primary" color="#ff9854" @click="showAddPaymentPopup = true">
                    添加支付方式
                </van-button>
            </div>

            <!-- 支付安全提示 -->
            <div class="payment-notice">
                <van-cell-group inset title="支付安全提示">
                    <van-cell>
                        <template #title>
                            <div class="notice-text">
                                <p><van-icon name="warn-o" color="#ff9854" /> 平台不会存储您的完整银行卡信息</p>
                                <p><van-icon name="shield-o" color="#ff9854" /> 支付过程全程加密保护</p>
                                <p><van-icon name="eye-o" color="#ff9854" /> 必要时我们会进行身份验证</p>
                            </div>
                        </template>
                    </van-cell>
                </van-cell-group>
            </div>
        </div>

        <!-- 添加支付方式弹窗 -->
        <van-popup v-model:show="showAddPaymentPopup" round position="bottom" :style="{ height: '70%' }">
            <div class="popup-content">
                <div class="popup-title">添加支付方式</div>

                <van-tabs v-model:active="activeTab">
                    <van-tab title="支付宝">
                        <van-form @submit="addAliPay">
                            <van-field v-model="alipayForm.account" name="account" label="支付宝账号" placeholder="请输入支付宝账号"
                                :rules="[{ required: true, message: '请输入支付宝账号' }]" />
                            <van-field v-model="alipayForm.name" name="name" label="账号名称" placeholder="请输入账号名称"
                                :rules="[{ required: true, message: '请输入账号名称' }]" />
                            <van-cell title="设置为默认支付方式">
                                <template #right-icon>
                                    <van-switch v-model="alipayForm.isDefault" size="24" />
                                </template>
                            </van-cell>
                            <div class="form-actions">
                                <van-button round block type="primary" color="#1989fa"
                                    native-type="submit">添加</van-button>
                                <van-button round block type="default"
                                    @click="showAddPaymentPopup = false">取消</van-button>
                            </div>
                        </van-form>
                    </van-tab>

                    <van-tab title="微信支付">
                        <van-form @submit="addWechatPay">
                            <van-field v-model="wechatForm.account" name="account" label="微信账号" placeholder="请输入微信账号"
                                :rules="[{ required: true, message: '请输入微信账号' }]" />
                            <van-field v-model="wechatForm.name" name="name" label="账号名称" placeholder="请输入账号名称"
                                :rules="[{ required: true, message: '请输入账号名称' }]" />
                            <van-cell title="设置为默认支付方式">
                                <template #right-icon>
                                    <van-switch v-model="wechatForm.isDefault" size="24" />
                                </template>
                            </van-cell>
                            <div class="form-actions">
                                <van-button round block type="primary" color="#07c160"
                                    native-type="submit">添加</van-button>
                                <van-button round block type="default"
                                    @click="showAddPaymentPopup = false">取消</van-button>
                            </div>
                        </van-form>
                    </van-tab>

                    <van-tab title="银行卡">
                        <van-form @submit="addCreditCard">
                            <van-field v-model="cardForm.account" name="account" label="卡号" type="tel" maxlength="19"
                                formatter="formatCardNumber" placeholder="请输入银行卡号" :rules="[
                                    { required: true, message: '请输入银行卡号' },
                                    { pattern: /^[0-9 ]{16,19}$/, message: '请输入有效的银行卡号' }
                                ]" />
                            <van-field v-model="cardForm.name" name="name" label="持卡人" placeholder="请输入持卡人姓名"
                                :rules="[{ required: true, message: '请输入持卡人姓名' }]" />
                            <van-field v-model="cardForm.expiry" name="expiry" label="有效期" placeholder="MM/YY" :rules="[
                                { required: true, message: '请输入有效期' },
                                { pattern: /^\d{2}\/\d{2}$/, message: '有效期格式为MM/YY' }
                            ]" />
                            <van-field v-model="cardForm.cvv" name="cvv" label="CVV" type="tel" maxlength="3"
                                placeholder="卡背后3位数字" :rules="[
                                    { required: true, message: '请输入CVV' },
                                    { pattern: /^\d{3}$/, message: 'CVV应为3位数字' }
                                ]" />
                            <van-cell title="设置为默认支付方式">
                                <template #right-icon>
                                    <van-switch v-model="cardForm.isDefault" size="24" />
                                </template>
                            </van-cell>
                            <div class="form-actions">
                                <van-button round block type="primary" color="#ee0a24"
                                    native-type="submit">添加</van-button>
                                <van-button round block type="default"
                                    @click="showAddPaymentPopup = false">取消</van-button>
                            </div>
                        </van-form>
                    </van-tab>
                </van-tabs>
            </div>
        </van-popup>

        <!-- 删除确认弹窗 -->
        <van-dialog v-model:show="showDeleteDialog" title="删除支付方式" show-cancel-button :before-close="handleDialogClose">
            确定要删除该支付方式吗？
        </van-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant'
import useProfileStore from '@/stores/modules/profile'

const router = useRouter()
const profileStore = useProfileStore()
const payments = computed(() => profileStore.payments)

// 表单数据
const alipayForm = reactive({
    account: '',
    name: '支付宝',
    type: 'alipay',
    isDefault: false
})

const wechatForm = reactive({
    account: '',
    name: '微信支付',
    type: 'wechat',
    isDefault: false
})

const cardForm = reactive({
    account: '',
    name: '',
    type: 'creditCard',
    expiry: '',
    cvv: '',
    isDefault: false
})

// 弹窗控制
const showAddPaymentPopup = ref(false)
const showDeleteDialog = ref(false)
const activeTab = ref(0)
const deletePaymentId = ref(null)

// 初始化数据
onMounted(async () => {
    await profileStore.fetchPaymentMethods()
})

// 返回按钮
const onClickLeft = () => {
    router.back()
}

// 根据支付类型获取图标
const getPaymentIcon = (type) => {
    const icons = {
        alipay: 'alipay',
        wechat: 'wechat',
        creditCard: 'credit-pay'
    }
    return icons[type] || 'cash-back-record'
}

// 根据支付类型获取颜色
const getPaymentColor = (type) => {
    const colors = {
        alipay: '#1989fa',
        wechat: '#07c160',
        creditCard: '#ee0a24'
    }
    return colors[type] || '#ff9854'
}

// 隐藏部分账号信息
const hideAccount = (account) => {
    if (!account) return ''

    // 处理信用卡号
    if (account.includes('*')) return account

    // 判断是否为手机号
    if (/^\d{11}$/.test(account)) {
        return account.substring(0, 3) + '****' + account.substring(7)
    }

    // 处理邮箱
    if (account.includes('@')) {
        const parts = account.split('@')
        const name = parts[0]
        const domain = parts[1]
        let hiddenName = name.substr(0, Math.min(3, name.length))
        for (let i = 0; i < Math.min(name.length - 3, 5); i++) {
            hiddenName += '*'
        }
        return hiddenName + '@' + domain
    }

    // 其他情况
    if (account.length <= 4) return account
    return account.substring(0, 2) + '****' + account.substring(account.length - 2)
}

// 添加支付宝账号
const addAliPay = async () => {
    await addPaymentMethod({
        ...alipayForm
    })
}

// 添加微信支付
const addWechatPay = async () => {
    await addPaymentMethod({
        ...wechatForm
    })
}

// 添加信用卡
const addCreditCard = async () => {
    await addPaymentMethod({
        ...cardForm
    })
}

// 通用添加支付方式
const addPaymentMethod = async (paymentData) => {
    showLoadingToast({
        message: '添加中...',
        forbidClick: true,
        duration: 0
    })

    try {
        if (paymentData.isDefault) {
            // 如果设置为默认，先将其他支付方式设为非默认
            payments.value.forEach(item => {
                item.isDefault = false
            })
        }

        const result = await profileStore.addPayment(paymentData)

        if (result.success) {
            showSuccessToast(result.message)
            showAddPaymentPopup.value = false

            // 重置表单
            alipayForm.account = ''
            alipayForm.isDefault = false

            wechatForm.account = ''
            wechatForm.isDefault = false

            cardForm.account = ''
            cardForm.name = ''
            cardForm.expiry = ''
            cardForm.cvv = ''
            cardForm.isDefault = false
        } else {
            showFailToast(result.message)
        }
    } catch (error) {
        showFailToast('添加失败')
    } finally {
        closeToast()
    }
}

// 设置默认支付方式
const setDefault = async (id) => {
    showLoadingToast({
        message: '设置中...',
        forbidClick: true,
        duration: 0
    })

    try {
        // 更新支付列表中的默认状态
        const updatedPayments = payments.value.map(item => ({
            ...item,
            isDefault: item.id === id
        }))

        // 模拟请求
        setTimeout(() => {
            profileStore.payments = updatedPayments
            showSuccessToast('设置成功')
        }, 500)
    } catch (error) {
        showFailToast('设置失败')
    } finally {
        closeToast()
    }
}

// 删除支付方式
const deletePayment = (id) => {
    deletePaymentId.value = id
    showDeleteDialog.value = true
}

// 处理删除确认
const handleDialogClose = (action) => {
    if (action === 'confirm') {
        confirmDeletePayment()
    }
    return true
}

// 确认删除支付方式
const confirmDeletePayment = async () => {
    if (!deletePaymentId.value) return

    showLoadingToast({
        message: '删除中...',
        forbidClick: true,
        duration: 0
    })

    try {
        // 过滤支付列表，模拟删除
        const updatedPayments = payments.value.filter(item => item.id !== deletePaymentId.value)

        // 模拟请求
        setTimeout(() => {
            profileStore.payments = updatedPayments
            showSuccessToast('删除成功')
        }, 500)
    } catch (error) {
        showFailToast('删除失败')
    } finally {
        closeToast()
        deletePaymentId.value = null
    }
}
</script>

<style lang="less" scoped>
.payment {
    background-color: #f7f8fa;
    min-height: 100vh;
    padding-bottom: 20px;
}

.payment-content {
    padding: 12px;
}

.payment-list {
    margin-bottom: 16px;
}

.default-payment {
    background-color: #fff9f0;
}

.payment-item {
    display: flex;
    align-items: center;
}

.payment-icon {
    margin-right: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #f8f8f8;
}

.payment-info {
    flex: 1;
}

.payment-name {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 4px;
    display: flex;
    align-items: center;
}

.payment-name .van-tag {
    margin-left: 8px;
}

.payment-account,
.payment-expiry {
    font-size: 12px;
    color: #999;
    line-height: 1.3;
}

.payment-actions {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.add-payment-btn {
    margin: 20px 0;
}

.notice-text {
    font-size: 12px;
    color: #666;
    line-height: 1.8;
}

.notice-text p {
    margin: 4px 0;
    display: flex;
    align-items: center;
}

.notice-text .van-icon {
    margin-right: 8px;
}

.popup-content {
    padding: 20px 16px;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.popup-title {
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
}

.form-actions {
    margin-top: 24px;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.van-tabs {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.van-tabs__content {
    flex: 1;
    overflow-y: auto;
}

.empty-state {
    padding: 40px 0;
}
</style>